package com.laogao.handle;

import com.laogao.common.AjaxResult;
import com.laogao.exception.AdxException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 异常处理器
 * @author laogao
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(AdxException.class)
    public AjaxResult AdxExceptionHandler(AdxException e) {
        log.error("出现了异常！ {}", e);
        return AjaxResult.error(e.getCode(), e.getMsg());
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public AjaxResult handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        return AjaxResult.error("运行时异常:" + e.getMessage());
    }

    /**
     * SpringMVC参数绑定，Validator校验不正确
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult bindExceptionHandler(BindException e) {
        FieldError fieldError = e.getFieldError();
        log.error("出现了异常！ {}", e);
        assert fieldError != null;
        return AjaxResult.error(fieldError.getDefaultMessage());
    }
}